﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DeskTopSeting.aspx.cs"  Inherits="ZX.WebApp.Extend.DeskTopSeting" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/reset-fonts-grids/reset-fonts-grids.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/menu/assets/skins/sam/menu.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
    <link type="text/css" rel="stylesheet" href="../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <!--begin custom header content for this example-->
    <style type="text/css">
        .yui-skin-sam table {
	        width: 100%;
        }
        

        #button-example-form fieldset, 
        #button-example-form fieldset div {
            border: 2px groove #ccc;
            margin: .5em;
            padding: .5em;
        }

        .yui-button#pushbutton2 button,
        .yui-button#pushbutton5 button, 
        .yui-button .Add button {
            background: url(../button/assets/add.gif) center center no-repeat;
            text-indent: -4em;
            overflow: hidden;
            padding: 0 .75em;
            width: 2em;
            *margin-left: 4em;   /* IE only */
            *padding: 0 1.75em;  /* IE only */

        }
    
        .yui-button#pushbutton3 button,
        .yui-button#pushbutton6 button, 
        .yui-button#pushbutton9 button {

            padding-left: 2em;
            background: url(../button/assets/add.gif) 10% 50% no-repeat;
    
        }
        <% =DataTableCss %>
    </style>
    <script src="../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <!--end custom header content for this example-->
    <!-- Dependencies -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <!-- OPTIONAL: JSON Utility (for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <!-- OPTIONAL: Calendar (enables calendar editors) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <!-- Source files -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script src="../Scripts/Appjs/model.TrSubjectInfo.js" type="text/javascript"></script>
    <script src="../Scripts/CombinButton.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        //var selectedRow = null;//当选行！
        function getSelected(v, t) {
            var recordID = mDataTable.getSelectedRows()[0];
            var record = mDataTable.getRecord(recordID);
            //alert(v);
            record._oData["Depts"] = v.toString();
            //alert(f+":"+record._oData[f]);
            record._oData["IsChanged"] = true;
            //alert(record._oData["Depts"]);
        }

        function selectDeptment() {
            var recordID = mDataTable.getSelectedRows()[0];
            var record = mDataTable.getRecord(recordID);
            //alert(record._oData["OperateRangeType"]);
            if (record._oData["OperateRangeType"].substring(0, 1) == "3") {
                var src="";
                var entityName = "DatDepartment";
                if (typeof (editlist) == "undefined") {
                   src = "../EditWidows/YUITree.aspx?r=" + Math.random() + "&entity=" + entityName + "&masterPara=DatDepartment|DeptName|DeptID|ParentID|DeptPath|True";
                   parent.ShowDialog(getSelected, id, src)
                } else {
                   src = "../EditWidows/YUITree.aspx?r=" + Math.random() + "&entity=" + entityName + "&masterPara=DatDepartment|DeptName|DeptID|ParentID|DeptPath|True";
                    ShowDialog(getSelected, id, src)
                }
            }
            else {
                alert("请选择自定义部门!");
            }
        }
    </script>
</head>
<body class="yui-skin-sam">
    <form id="form1" runat="server">
    <!-- 工具栏 -->
    <div id="listpage">
        <div id="data">
            <div id="json">
            </div>
        </div>
    </div>

    </form>
     <form id="form2" action="AjaxData/DataSave.aspx">
    <textarea style="display: none" id="jsonDataContent" rows="2" cols="2" name="jsonDataContent"></textarea>
    </form>
</body>
<script language="javascript" type="text/javascript">
    // 定义数组的方法
    if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function (elt /*, from*/) { var len = this.length; var from = Number(arguments[1]); if (isNaN(from)) { from = len - 1; } else { from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; else if (from >= len) from = len - 1; } for (; from > -1; from--) { if (from in this && this[from] === elt) return from; } return -1; }; } 
</script>
<script type="text/javascript">
    // 
    //
    //
    var const_entityID = "<% =EntityId %>",
        const_entityName = "<% =EntityName %>",
        const_EditEntity = "<% =EditEntity %>",
        selectControl=null;
    
    (function () {
        var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

        Event.onDOMReady(function () {
            var layout = new YAHOO.widget.Layout({
                units: [
                //{ position: 'top',height: 35, body: 'toolbar', gutter: '1 1 1 1', scroll: null, zIndex: 2 },
                //{ position: 'left', header: '功能模块', width: 250, body: 'left', gutter: '1 5 1 1', collapse: true, scroll: true, zIndex: 1, resize: true },
                {position: 'center', body: 'data', gutter: '1 1', scroll: true }
                //{position: 'bottom', height: 30, body: 'bottom', gutter: '1 1'}
            ]
            });
            layout.render();
        });
    })();

 
    //新增
    var fnAdd = function(){
        document.getElementById("EditUIWindow").src="AutoEditUI.aspx?r="+Math.random()+"&entity="+const_EditEntity;
        YAHOO.example.container.dialog1.show();
    }

    //删除
    function DeleteData(SaveUrl,func)
    {
            var recs = this.mDataTable.getRecordSet();
            YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                success: function (res) {
                    try {
                        var str = res.responseText;
   
                        if(str=="1"){
                            alert("数据删除成功");
                            if(typeof(func)=="function"){
                            func();
                            }
                            //parent.closeWin();
                        }
                        else
                        {
                            alert(str+"\n"+"数据删除失败!");
                        }
                    }
                    catch (e) {
                    }
                    finally {
                    }
                },
                failure: function (error) {
                    alert("数据错误：" + error.statusText);
                }
            }, null);
    }
    


    //删除 
    var fnDelete = function(){
            var recordID = myDataTable.getSelectedRows()[0];
            record = myDataTable.getRecord(recordID);
            DeleteData("AjaxData/DataSave.aspx?r=" + Math.random()+"&action=delete&entity="+const_EditEntity+"&id="+record.getData(const_entityID),LoadData);           
    }

    
    //查询
    var fnQuery = function(){
    }
    //导出
    var fnExport = function(){
    }
    //报表
    var fnReport = function(){
    }


        //问卷选择题目
    YAHOO.example.init = function () {

        // "click" event handler for each Button instance
        function onButtonClick(p_oEvent) {
                 YAHOO.log("You clicked button: " + this.get("id"), "info", "example1");
                 switch(this.get("id"))
                 { 
                    case "btnAddNew":
                         fnAdd();
                         break;
                    case "btnEdit":
                         fnEdit();
                          break;
                    case "btnDelete":
                         fnDelete();
                         break;
                    case "btnQuery":
                         fnQuery();
                         break;
                    case "btnExport":
                         fnExport();
                         break;
                    case "btnReport":
                         fnReport();
                         break;
                    case "btnChoseeSubject":
                        fnChoseeSubject();
                        break;
                    default:
                         fnAdd();
                         break;
                 }                        
        }

        // "contentready" event handler for the "pushbuttonsfrommarkup" <fieldset>
        YAHOO.util.Event.onContentReady("toolbar", function () {
            // Create Buttons using existing <input> elements as a data source
            var btnAddNew = new YAHOO.widget.Button("btnAddNew");
            var btnEdit = new YAHOO.widget.Button("btnEdit");
            var btnDelete = new YAHOO.widget.Button("btnDelete");
            var btnQuery = new YAHOO.widget.Button("btnQuery");
   
            btnAddNew.on("click", onButtonClick);
            btnEdit.on("click", onButtonClick);
            btnDelete.on("click", onButtonClick);
            btnQuery.on("click", onButtonClick);
        });


    } ();

    function AddButton() {
        var button = document.createElement('button');
        button.innerHTML = 'add tab';
        YAHOO.util.Event.on(button, 'click', addTab);
        tabView.appendChild(button);
    }


    //DataTable 
    var mDataTable;
    //刷新数据
    function LoadData()
    {
       BindData();
    }

    //关闭窗口
    function closeWin(){
        LoadData();
        YAHOO.example.container.dialog1.hide();
    }

    function ShowDialog(hidControl)
    {
         selectControl=hidControl;
         YAHOO.example.container.dialog2.show();
    }

    //数据绑定
    function BindData() {
        YAHOO.example.XHR_JSON = function () {

            var arrRangeType = [{ Text: " ", Value: " " }, { Text: "本人", Value: "0 " }, { Text: "本部门", Value: "1 " }, { Text: "全部", Value: "2 " }, { Text: "自定义部门", Value: "3 " }, { Text: "自定义条件", Value: "4 "}];
            var formatOpration = function (elCell, oRecord, oColumn, sData) {
                var arr = [];
                if (sData != null) {
                    var str1 = oRecord.getData("BarItem"),
                        str2 = oRecord.getData("BarItems"),
                        s = sData.split(","),
                        s1 = str2.split(","),
                        ArrStr1 = str1.split(",");

                    for (var i = 0; i < s.length; i++) {
                        var sHtml;

                        if (ArrStr1.lastIndexOf(s[i]) > -1) {
                            //alert(s[i]);
                            sHtml = "<input id='" + s[i] + "_" + oRecord.getData("FunctionId") + "' name='" + s[i] + "' type='checkbox' checked='true' value='" + s[i] + "'>" + s1[i] + "  ";
                        }
                        else {
                            sHtml = "<input id='" + s[i] + "_" + oRecord.getData("FunctionId") + "' name='" + s[i] + "' type='checkbox' value='" + s[i] + "'>" + s1[i] + "  ";
                        }
                        arr.push(sHtml);
                    }
                }

                elCell.innerHTML = "<div id='" + oRecord.getData("FunctionId") + "'>" + arr.join("") + "</div>";
            };

            var formatSelect = function (elCell, oRecord, oColumn, sData) {
                var str1 = [];
                str1.push("<select name='OperateRangeType'  onchange='ChangeEvent(this);'>");
                for (i = 0; i < arrRangeType.length; i++) {
                    //alert(sData + ":" + arrRangeType[i].Value);
                    if (arrRangeType[i].Value === sData) {
                        str1.push("<option value='" + arrRangeType[i].Value + "' selected>" + arrRangeType[i].Text + "</option>");
                    }
                    else {
                        str1.push("<option value='" + arrRangeType[i].Value + "'>" + arrRangeType[i].Text + "</option>");
                    }
                }
                str1.push("</select>");
                elCell.innerHTML = str1.join("");
            }
            var formatSelectDept = function (elCell, oRecord, oColumn, sData) {
                //elCell.innerHTML = "<button onclick=\"javascript:selectDept('"+oRecord.getData("Depts")+"')\">选择部门</button>";
                elCell.innerHTML = "<button id=\"btnSelDept\"  onclick=\"selectDeptment()\" sel=\"M\" type=\"button\">选择</button>";
                //<input type="hidden"  id="DeptID" name="DeptID" value="333fe8ed-ca2a-497a-a88c-3bb4fb3a1a57"/><input type="text" id="txtDeptID" value="中旭集团" readonly="readonly" name="中旭集团" style="width:193px" class="yui-dept"/><button id="btnDeptID" name="D" type="button">选择</button>
            }
            var myColumnDefs = [
                     { key: 'FunctionId', label: '模块ID', width: 100, sortable: true },
                     { key: 'Name', label: '模块名称', width: 100, sortable: true },
                     { key: 'OperateRangeType', label: '数据范围', formatter: formatSelect, width: 100, sortable: true },
                     { key: 'Opration', label: '操作功能', formatter: formatOpration, width: 250, sortable: true },
                     { key: 'Depts', label: '自定义部门', formatter:formatSelectDept,width: 100, sortable: true },
                     { key: 'Condition', label: '条件', width: 200, sortable: true }
            ];

            var myDataSource = new YAHOO.util.DataSource("AjaxData/JSONList.aspx?");
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            myDataSource.connXhrMode = "queueRequests";
            myDataSource.responseSchema = {
                resultsList: "rows",
                //fields: ["EntityName", "THCaption", "Field", { key: "Rating.AverageRating", parser: "number" }, "Width"]
                fields: ['IsChanged', 'OperateRangeType', 'FunctionId', 'iSun_Selected', 'Name', 'Opration', 'BarItem', 'BarItems', "RoleFunctionID", "Depts", "Condition"]
            };

            this.myDataTable = new YAHOO.widget.DataTable("json", myColumnDefs,
                    myDataSource, { initialRequest: "entity=" + const_entityName + "&order=<% =Order %>&r=" + Math.random() + "&zip=94089&results=10&output=json&condition=<% =Condition %>", selectionMode: "single" }, { height: "100%" });
            mDataTable = this.myDataTable;
            var mySuccessHandler = function () {
                this.set("sortedBy", null);
                this.onDataReturnAppendRows.apply(this, arguments);
            };
            var myFailureHandler = function () {
                this.showTableMessage(YAHOO.widget.DataTable.MSG_ERROR, YAHOO.widget.DataTable.CLASS_ERROR);
                this.onDataReturnAppendRows.apply(this, arguments);
            };
            var callbackObj = {
                success: mySuccessHandler,
                failure: myFailureHandler,
                scope: myDataTable
            };

            // 调用自定义双击行的方法
            var onRowDoubleClick = function () {
                //if(typeof(CustomDbClick)=="function")
                //{
                //CustomDbClick();
                //}
                var recordID = myDataTable.getSelectedRows()[0];
                var record = myDataTable.getRecord(recordID);
                var pId = record.getData("<%=EntityId%>");
                var selectRows = myDataTable.getSelectedRows();
                if (selectRows.length != null && selectRows.length == 1) {
                    var EntityName = "<%=EntityName %>";
                    CustomDbClick(EntityName, pId);
                }
                else {
                    alert("请选中一行");
                }
            };

            // Subscribe to events for row selection 
            this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
            this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
            this.myDataTable.subscribe("rowClickEvent", this.myDataTable.onEventSelectRow);
            this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
            this.myDataTable.subscribe("checkboxClickEvent", function (oArgs) {
                var elCheckbox = oArgs.target;
                var oRecord = this.getRecord(elCheckbox);
                if (elCheckbox.id.indexOf("yui") > -1) {
                    //alert(elCheckbox.id);
                    oRecord.setData("iSun_Selected", elCheckbox.checked);
                }
                else {
                    if (elCheckbox.checked) {
                        if (oRecord._oData["BarItem"].toString().indexOf(elCheckbox.value) < 0) {
                            oRecord._oData["BarItem"] = oRecord._oData["BarItem"] + "," + elCheckbox.value;
                        }
                        oRecord._oData["IsChanged"] = true;
                    }
                    else {
                        oRecord._oData["BarItem"] = oRecord._oData["BarItem"].replace(elCheckbox.value, "").replace(",,", ",");
                        oRecord._oData["IsChanged"] = true;
                    }
                }
            });

            // Programmatically select the first row 
            this.myDataTable.selectRow(this.myDataTable.getTrEl(0));
            hideCol();
        } ();
    }
    

    //隐藏/栏位
    function hideCol(){ mDataTable.hideColumn(parseInt(0)); mDataTable.refreshView(); };
    YAHOO.util.Event.addListener(window, "load", BindData);
    
    function Save()
    {
        var list =this.mDataTable.getRecordSet()._records;
        var elist = [];
        for(var i=0;i<list.length;i++)
        {
            //this.getRecordSet()._records[0]._oData["BarItem"]
            if(list[i]._oData["IsChanged"]==true)
            {
                elist.push(list[i]._oData);
            }
        }

        url = "AjaxData/DataSave.aspx";
        
        var jsonStr = YAHOO.lang.JSON.stringify(elist, ["RoleFunctionID", "BarItem", "OperateRangeType","Depts","Condition"]);
        document.getElementById("jsonDataContent").value = jsonStr;
        trySave();

    }


    //值改变事件
    var ChangeEvent = function (oArgs) {

        var f = oArgs.name;
        //alert(f);
        var v = oArgs.value;
        //alert(v);
        setValue(f, v);
    }

    ///f=字段名 v=值
    var setValue = function (f, v) {
        var recordID = mDataTable.getSelectedRows()[0];
        var record = mDataTable.getRecord(recordID);
        //alert(v);
        record._oData[f] = v;
        //alert(f+":"+record._oData[f]);
        record._oData["IsChanged"] = true;
    }

    var trySave = function () {
        // argument formId can be the id or name attribute value of the
        // HTML form, or an HTML form object.
        var formObject = document.getElementById('form2');
        YAHOO.util.Connect.setForm(formObject);
        // This example facilitates a POST transaction.  The POST data(HTML form)
        // are initialized when calling setForm(), and it is automatically
        // included when calling asyncRequest.
        var cObj = YAHOO.util.Connect.asyncRequest('POST', url + "?flag=1&action=setRight", callback);
      }
      var callback = {
          success: function (res) {
              try {
                  var str = res.responseText;
                  if (str == "1") {
                      alert("数据保存成功");
                      if (action == 'insert') {
                          parent.fnAddRow(instance[0]);
                      } else {
                          parent.fnUpdateRow(instance[0]);
                      }
                      parent.closeWin();
                  }
                  else {
                      showMessage()
                      alert(str + "\n" + "数据保存失败!");
                  }
              }
              catch (e) {
              }
              finally {
              } 
          },
          failure: function (error) {
              alert("数据错误：" + error.statusText);
          }
      };
 </script>
</html>
